package com.corecmd.tcloud.tcimserver.im.common;

import com.corecmd.tcloud.tcimcommon.im.common.PacketCodeC;
import com.corecmd.tcloud.tcimcommon.im.domain.MessageRequestPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/20
 * @description :
 **/
@Slf4j
@Data
public class ImSessionHolder {
    public static final Map<String, NioSocketChannel> SESSIONHOLDERS = new ConcurrentHashMap<String, NioSocketChannel>(16);
    public static void put(String sessionId,NioSocketChannel channel){
        SESSIONHOLDERS.put(sessionId,channel);
    }
    public static void delete(String sessionId){
        SESSIONHOLDERS.keySet().removeIf(sessionId::equals);
    }
    public static NioSocketChannel get(String sessionId){
        return SESSIONHOLDERS.get(sessionId);
    }
    public static void broadcastMessage(MessageRequestPacket messagePacket,String ... exceptUsers) throws Exception{
        log.info("推送广播消息到客户端:"+messagePacket.toString());
        String strExcepUsers = StringUtils.join(exceptUsers,";");
        for (Map.Entry<String, NioSocketChannel> stringNioSocketChannelEntry : ImSessionHolder.SESSIONHOLDERS.entrySet()) {
            String currentClientId = stringNioSocketChannelEntry.getKey();
            if (strExcepUsers.contains(currentClientId)){
                continue;
            }
            NioSocketChannel currentClientChannel = stringNioSocketChannelEntry.getValue();
            String currentClientName = (String) currentClientChannel.attr(AttributeKey.valueOf("userName")).get();
            // 写数据
            try {
                ByteBuf buffer = new PacketCodeC().encode(messagePacket);
                ChannelFuture future = currentClientChannel.writeAndFlush(buffer).sync();
                log.info("推送广播消息给客户端："+currentClientName+(future.isSuccess()?"  成功":("  失败,原因:"+future.cause())));
            } catch (Exception e) {
                log.info("推送广播消息给客户端："+currentClientName+"异常",e);
            }
        }
    }
}
